import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/video.dart';
import '../../models/comment.dart';
import '../../api/api_service.dart';
import '../../config/app_theme.dart';
import '../../utils/date_util.dart';
import '../../providers/app_state.dart';

class VideoDetailScreen extends StatefulWidget {
  final Video video;

  const VideoDetailScreen({Key? key, required this.video}) : super(key: key);

  @override
  _VideoDetailScreenState createState() => _VideoDetailScreenState();
}

class _VideoDetailScreenState extends State<VideoDetailScreen> {
  final ApiService _apiService = ApiService();
  List<Comment> _comments = [];
  bool _isLoading = true;
  final TextEditingController _commentController = TextEditingController();
  bool _isPostingComment = false;
  bool _isPlaying = true;

  @override
  void initState() {
    super.initState();
    _loadComments();
    
    // 添加到浏览历史
    Provider.of<AppState>(context, listen: false)
        .addVideoToRecentlyViewed(widget.video.id);
  }

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  Future<void> _loadComments() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final comments = await _apiService.getCommentsByVideoId(widget.video.id);
      setState(() {
        _comments = comments;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading comments: $e');
    }
  }

  Future<void> _postComment() async {
    final content = _commentController.text.trim();
    if (content.isEmpty) return;

    setState(() {
      _isPostingComment = true;
    });

    try {
      // 模拟发布评论
      await Future.delayed(Duration(seconds: 1));
      
      final newComment = Comment(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        postId: widget.video.id, // 使用视频ID作为postId
        userId: 'current_user',
        userName: '我', // 假设当前用户名
        userAvatar: 'https://via.placeholder.com/40',
        content: content,
        createdAt: DateTime.now(),
        likes: 0,
      );

      setState(() {
        _comments.insert(0, newComment);
        _isPostingComment = false;
      });
      _commentController.clear();
      
      // 隐藏键盘
      FocusScope.of(context).unfocus();
    } catch (e) {
      setState(() {
        _isPostingComment = false;
      });
      print('Error posting comment: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('评论发布失败，请重试')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final appState = Provider.of<AppState>(context);
    final bool isFavorite = appState.favoriteVideos.contains(widget.video.id);

    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        children: [
          // 视频播放区域
          _buildVideoPlayer(),
          
          // 评论和信息区域
          Expanded(
            child: Container(
              color: Colors.white,
              child: Column(
                children: [
                  // 视频信息和操作按钮
                  _buildVideoInfo(isFavorite, appState),
                  
                  // 评论列表
                  Expanded(
                    child: _buildCommentList(),
                  ),
                  
                  // 评论输入框
                  _buildCommentInput(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVideoPlayer() {
    return Stack(
      children: [
        // 视频播放器（这里使用图片代替）
        AspectRatio(
          aspectRatio: 16 / 9,
          child: Container(
            color: Colors.black,
            child: Stack(
              alignment: Alignment.center,
              children: [
                Image.network(
                  widget.video.coverUrl,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                ),
                if (!_isPlaying)
                  IconButton(
                    icon: Icon(
                      Icons.play_circle_outline,
                      color: Colors.white,
                      size: 64,
                    ),
                    onPressed: () {
                      setState(() {
                        _isPlaying = true;
                      });
                    },
                  ),
              ],
            ),
          ),
        ),
        
        // 返回按钮
        SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                IconButton(
                  icon: Icon(Icons.arrow_back, color: Colors.white),
                  onPressed: () => Navigator.of(context).pop(),
                ),
                IconButton(
                  icon: Icon(Icons.more_vert, color: Colors.white),
                  onPressed: () {
                    // TODO: 显示更多选项菜单
                  },
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildVideoInfo(bool isFavorite, AppState appState) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 视频标题
          Text(
            widget.video.title,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 8),
          
          // 视频描述
          Text(
            widget.video.description,
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[700],
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
          SizedBox(height: 16),
          
          // 用户信息和操作按钮
          Row(
            children: [
              // 用户头像
              CircleAvatar(
                radius: 16,
                backgroundImage: NetworkImage(widget.video.userAvatar),
              ),
              SizedBox(width: 8),
              
              // 用户名
              Text(
                widget.video.userName,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(width: 8),
              
              // 关注按钮
              OutlinedButton(
                onPressed: () {
                  // TODO: 关注功能
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('关注功能即将上线')),
                  );
                },
                child: Text('关注'),
                style: OutlinedButton.styleFrom(
                  primary: AppTheme.primaryColor,
                  side: BorderSide(color: AppTheme.primaryColor),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 0),
                  minimumSize: Size(60, 30),
                ),
              ),
              Spacer(),
              
              // 收藏按钮
              IconButton(
                icon: Icon(
                  isFavorite ? Icons.favorite : Icons.favorite_border,
                  color: isFavorite ? Colors.red : Colors.grey,
                ),
                onPressed: () {
                  appState.toggleFavoriteVideo(widget.video.id);
                },
              ),
              
              // 分享按钮
              IconButton(
                icon: Icon(Icons.share, color: Colors.grey),
                onPressed: () {
                  // TODO: 分享功能
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('分享功能即将上线')),
                  );
                },
              ),
            ],
          ),
          
          // 分割线
          Divider(height: 32),
          
          // 评论头部
          Row(
            children: [
              Text(
                '评论 (${_comments.length})',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Spacer(),
              if (_comments.isNotEmpty)
                Text(
                  '最新',
                  style: TextStyle(
                    fontSize: 14,
                    color: AppTheme.primaryColor,
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildCommentList() {
    if (_isLoading) {
      return Center(child: CircularProgressIndicator());
    }

    if (_comments.isEmpty) {
      return Center(
        child: Text(
          '暂无评论，快来发表第一条评论吧!',
          style: TextStyle(color: Colors.grey),
        ),
      );
    }

    return ListView.separated(
      physics: BouncingScrollPhysics(),
      itemCount: _comments.length,
      separatorBuilder: (context, index) => Divider(height: 1),
      itemBuilder: (context, index) {
        final comment = _comments[index];
        return _buildCommentItem(comment);
      },
    );
  }

  Widget _buildCommentItem(Comment comment) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CircleAvatar(
            radius: 16,
            backgroundImage: NetworkImage(comment.userAvatar),
          ),
          SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      comment.userName,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                      ),
                    ),
                    Spacer(),
                    Text(
                      DateUtil.timeAgo(comment.createdAt),
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 4),
                Text(
                  comment.content,
                  style: TextStyle(fontSize: 14),
                ),
                SizedBox(height: 8),
                Row(
                  children: [
                    InkWell(
                      onTap: () {
                        // TODO: 评论点赞功能
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(4.0),
                        child: Row(
                          children: [
                            Icon(
                              Icons.thumb_up_outlined,
                              size: 16,
                              color: Colors.grey,
                            ),
                            SizedBox(width: 4),
                            Text(
                              comment.likes.toString(),
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(width: 16),
                    InkWell(
                      onTap: () {
                        // TODO: 回复评论功能
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(4.0),
                        child: Text(
                          '回复',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCommentInput() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            offset: Offset(0, -1),
            blurRadius: 3,
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _commentController,
              decoration: InputDecoration(
                hintText: '写下你的评论...',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: Colors.grey[100],
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 8,
                ),
              ),
              maxLines: 1,
            ),
          ),
          SizedBox(width: 8),
          _isPostingComment
              ? SizedBox(
                  width: 36,
                  height: 36,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                    ),
                  ),
                )
              : IconButton(
                  icon: Icon(Icons.send, color: AppTheme.primaryColor),
                  onPressed: _postComment,
                ),
        ],
      ),
    );
  }
} 